
package com.wwj.pay.service.impl;

import com.wwj.pay.entity.ApyAccount;
import com.wwj.pay.entity.mapper.ApyAccountMapper;
import com.wwj.pay.enums.PayType;
import com.wwj.pay.service.IApyAccountService;
import com.wwj.pay.service.PayResponse;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: egan
 * @email egzosn@gmail.com
 * @date 2016/11/18 1:11
 */
@Service
public class ApyAccountServiceImpl implements IApyAccountService {

    @Resource
    private ApyAccountMapper apyAccountMapper;

    @Resource
    private AutowireCapableBeanFactory spring;

    /**
     * 缓存
     */
    private final static Map<Integer, PayResponse> payResponses = new HashMap<Integer, PayResponse>();

    //private final static Map<Object, PayResponse> payResponses = new HashMap<Object, PayResponse>();

    private final static Map<PayType, Integer> payResponseKeys = new HashMap<PayType, Integer>();

    /**
     *  获取支付响应
     * @param id 账户id
     * @return
     */
    public PayResponse getPayResponse(Integer id) {
        PayResponse payResponse = payResponses.get(id);
        if (payResponse  == null) {
            ApyAccount apyAccount = apyAccountMapper.getById(id);
            if (apyAccount == null) {
                throw new IllegalArgumentException ("无法查询");
            }
            payResponse = new PayResponse();
            spring.autowireBean(payResponse);
            payResponse.init(apyAccount);
            payResponses.put(id, payResponse);
            payResponseKeys.put(apyAccount.getPayType(),id);
            // 查询
        }
        return payResponse;
    }

    public PayResponse getPayResponse(PayType payType) {
        Integer payId = payResponseKeys.get(payType);
        if(payId == null) {
            ApyAccount apyAccount = apyAccountMapper.selectByPayType(payType.name());
            payId = apyAccount.getPayId();
        }
        return this.getPayResponse(payId);
    }

    @Override
    public Integer getPayId(PayType payType) {
        Integer payId = payResponseKeys.get(payType);
        if(payId == null) {
            ApyAccount apyAccount = apyAccountMapper.selectByPayType(payType.name());
            payId = apyAccount.getPayId();
        }
        return payId;
    }
}
